"""
/patient-data 路由调用 save_patient_data 函数的流程图
"""

import matplotlib.pyplot as plt
import matplotlib.patches as patches

# 设置中文字体
plt.rcParams['font.sans-serif'] = ['SimHei', 'Arial Unicode MS', 'DejaVu Sans']
plt.rcParams['axes.unicode_minus'] = False

def draw_flowchart():
    # 创建图形和轴
    fig, ax = plt.subplots(1, 1, figsize=(12, 10))
    ax.set_xlim(0, 12)
    ax.set_ylim(0, 10)
    ax.axis('off')  # 隐藏坐标轴

    # 定义节点位置和内容
    nodes = [
        {"pos": (6, 9), "text": "1. 启动应用\npython main.py", "width": 3, "height": 1},
        {"pos": (6, 7.5), "text": "2. 创建FastAPI应用\ncreate_app()", "width": 3, "height": 1},
        {"pos": (6, 6), "text": "3. 注册路由\napp.include_router(router)", "width": 3.5, "height": 1},
        {"pos": (6, 4.5), "text": "4. 包含患者数据路由\nrouter.include_router(patient_data_router)", "width": 4.5, "height": 1},
        {"pos": (6, 3), "text": "5. 路由定义\n@router.post('/')\nasync def save_patient_data()", "width": 4, "height": 1.5},
        {"pos": (2, 1.5), "text": "6a. 客户端发送请求\nPOST /patient-data/", "width": 3, "height": 1},
        {"pos": (6, 1.5), "text": "6b. FastAPI匹配路由\n根据装饰器匹配", "width": 3, "height": 1},
        {"pos": (10, 1.5), "text": "6c. 调用函数\nsave_patient_data(request)", "width": 3, "height": 1},
        {"pos": (6, 0.5), "text": "7. 处理请求并返回响应", "width": 3, "height": 0.8}
    ]

    # 绘制节点
    for node in nodes:
        x, y = node["pos"]
        width, height = node["width"], node["height"]
        
        # 绘制矩形框
        rect = patches.Rectangle((x - width/2, y - height/2), width, height, 
                                linewidth=1, edgecolor='black', facecolor='lightblue')
        ax.add_patch(rect)
        
        # 添加文本
        ax.text(x, y, node["text"], ha='center', va='center', fontsize=10)

    # 绘制连接箭头
    arrows = [
        [(6, 8.5), (6, 8)],
        [(6, 7), (6, 6.5)],
        [(6, 5.5), (6, 5)],
        [(6, 4), (6, 3.75)],
        [(6, 2.25), (6, 2)],
        [(6, 1), (2, 1.5)],
        [(6, 1), (6, 1.5)],
        [(6, 1), (10, 1.5)],
        [(2, 1), (6, 0.5)],
        [(6, 1), (6, 0.9)],
        [(10, 1), (6, 0.5)]
    ]
    
    for start, end in arrows:
        ax.annotate('', xy=end, xytext=start,
                    arrowprops=dict(arrowstyle='->', lw=1.5, color='black'))

    # 添加标题
    ax.text(6, 9.7, '/patient-data 路由调用 save_patient_data 函数流程图', 
            ha='center', va='center', fontsize=16, weight='bold')

    # 保存图像
    plt.tight_layout()
    plt.savefig('patient_data_route_flow.png', dpi=300, bbox_inches='tight')
    plt.show()

if __name__ == "__main__":
    draw_flowchart()
    print("流程图已生成：patient_data_route_flow.png")